<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WebSocketService
{
    protected $baseUrl;
    protected $enabled;

    public function __construct()
    {
        $this->enabled = config('websocket.enabled', false);
        $this->baseUrl = config('websocket.base_url', 'http://localhost:8080');
    }

    /**
     * 检查WebSocket是否启用
     *
     * @return bool
     */
    public function isEnabled()
    {
        return $this->enabled;
    }

    /**
     * 发送消息给指定用户
     *
     * @param int $userId
     * @param string $action
     * @param array $content
     * @param array $data
     * @return array|null
     */
    public function sendToUser(int $userId, string $action, array $content, array $data = [])
    {
        return $this->send([
            'type' => 'user',
            'to_user_id' => $userId,
            'action' => $action,
            'content' => $content,
            'data' => $data,
        ]);
    }

    /**
     * 发送消息给多个用户
     *
     * @param array $userIds
     * @param string $action
     * @param array $content
     * @param array $data
     * @return array|null
     */
    public function sendToUsers(array $userIds, string $action, array $content, array $data = [])
    {
        return $this->send([
            'type' => 'user',
            'to_user_ids' => $userIds,
            'action' => $action,
            'content' => $content,
            'data' => $data,
        ]);
    }

    /**
     * 广播消息
     *
     * @param string $action
     * @param array $content
     * @param array $data
     * @return array|null
     */
    public function broadcast(string $action, array $content, array $data = [])
    {
        return $this->send([
            'type' => 'broadcast',
            'action' => $action,
            'content' => $content,
            'data' => $data,
        ]);
    }

    /**
     * 发送系统通知
     *
     * @param int $userId
     * @param string $title
     * @param string $message
     * @param string $level
     * @param string|null $link
     * @return array|null
     */
    public function notify(int $userId, string $title, string $message, string $level = 'info', string $link = null)
    {
        return $this->sendToUser($userId, 'notify', [
            'title' => $title,
            'message' => $message,
            'level' => $level,
            'link' => $link,
        ]);
    }

    /**
     * 发送聊天消息
     *
     * @param int $fromUserId
     * @param int $toUserId
     * @param string $text
     * @param string|null $image
     * @param string|null $file
     * @param string|null $fileName
     * @return array|null
     */
    public function sendChatMessage(int $fromUserId, int $toUserId, string $text, string $image = null, string $file = null, string $fileName = null)
    {
        return $this->sendToUser($toUserId, 'chat', [
            'text' => $text,
            'image' => $image,
            'file' => $file,
            'file_name' => $fileName,
        ], [
            'from_user_id' => $fromUserId,
        ]);
    }

    /**
     * 发送请求
     *
     * @param array $data
     * @return array|null
     */
    protected function send(array $data)
    {
        // 如果WebSocket未启用，直接返回null
        if (!$this->enabled) {
            return null;
        }

        try {
            $timeout = config('websocket.timeout', 5);
            $response = Http::timeout($timeout)->post($this->baseUrl . '/api/send', $data);
            
            if ($response->successful()) {
                return $response->json();
            }
            
            Log::error('WebSocket服务请求失败', [
                'status' => $response->status(),
                'body' => $response->body(),
                'data' => $data,
            ]);
            
            return null;
        } catch (\Exception $e) {
            Log::error('WebSocket服务请求异常', [
                'message' => $e->getMessage(),
                'data' => $data,
            ]);
            return null;
        }
    }

    /**
     * 获取在线用户列表
     *
     * @return array
     */
    public function getOnlineUsers()
    {
        // 如果WebSocket未启用，返回空数组
        if (!$this->enabled) {
            return [];
        }

        try {
            $timeout = config('websocket.timeout', 5);
            $response = Http::timeout($timeout)->get($this->baseUrl . '/api/online-users');
            
            if ($response->successful()) {
                return $response->json('data', []);
            }
            
            return [];
        } catch (\Exception $e) {
            Log::error('获取在线用户列表失败', [
                'message' => $e->getMessage(),
            ]);
            return [];
        }
    }

    /**
     * 检查用户是否在线
     *
     * @param int $userId
     * @return bool
     */
    public function isUserOnline(int $userId)
    {
        // 如果WebSocket未启用，返回false
        if (!$this->enabled) {
            return false;
        }

        try {
            $timeout = config('websocket.timeout', 5);
            $response = Http::timeout($timeout)->get($this->baseUrl . '/api/user-online', [
                'user_id' => $userId,
            ]);
            
            if ($response->successful()) {
                return $response->json('data.is_online', false);
            }
            
            return false;
        } catch (\Exception $e) {
            Log::error('检查用户在线状态失败', [
                'message' => $e->getMessage(),
                'user_id' => $userId,
            ]);
            return false;
        }
    }

    /**
     * 获取用户连接数
     *
     * @param int $userId
     * @return int
     */
    public function getUserConnections(int $userId)
    {
        // 如果WebSocket未启用，返回0
        if (!$this->enabled) {
            return 0;
        }

        try {
            $timeout = config('websocket.timeout', 5);
            $response = Http::timeout($timeout)->get($this->baseUrl . '/api/user-online', [
                'user_id' => $userId,
            ]);
            
            if ($response->successful()) {
                return $response->json('data.connections', 0);
            }
            
            return 0;
        } catch (\Exception $e) {
            Log::error('获取用户连接数失败', [
                'message' => $e->getMessage(),
                'user_id' => $userId,
            ]);
            return 0;
        }
    }
}

